package com.sgcc.pda.greendao.dao.h5;

import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

import net.sqlcipher.database.SQLiteDatabase;

import java.util.HashMap;
import java.util.Map;

/**
 * 数据库管理类.
 *
 * @author SUPERFAN
 * @data 提供给H5业务应用的数据库操作类
 */

public class DBH5Manager {
    private static final String TAG = "DBH5Manager";

    private Context mContext;
    //默认的加密密钥 ：不进行加密
    private static final String DEFAULT_DB_ENCRYP_PASD = "12345678";

    private Map<String, DBH5OpenHelper> openHelperMap;//数据库处理集 key为数据库名
    private Map<String, String> encryptKeyMap;//数据库密钥集 key为数据库名

    private DBH5Manager() {
    }

    private static class Instance {
        private static final DBH5Manager DBH5MANAGER = new DBH5Manager();
    }

    public static DBH5Manager getInstance() {
        return Instance.DBH5MANAGER;
    }

    /**
     * 初始化   请一定初始化
     */
    public void init(Context context) {
        this.mContext = context;
        openHelperMap = new HashMap<>();
        encryptKeyMap = new HashMap<>();
    }

    /**
     * 初始化数据库：数据库名，加密密码，版本号（暂无用）
     * 调用此方法并不会创建数据库，只有在第一次创建表的时候，才会创建数据库
     * 数据库在 应用的私有目录下data/data/comg.sgcc.pda.data/databases
     *
     * @return
     * @dbName 数据库名
     * @dbEncrypPwd 加密密钥
     * @version 版本号 （暂时无用，更新使用更新字段方法）
     */
    public String initDatabase(@NonNull String dbName, String dbEncrypPwd, int version) {
        try {
            if (TextUtils.isEmpty(dbName)) {
                return "数据库名字不能为空";
            }
            DBH5OpenHelper dbh5OpenHelper = openHelperMap.get(dbName);
            if (dbh5OpenHelper == null) {
                dbh5OpenHelper = new DBH5OpenHelper(mContext, /*Environment.getDataDirectory().getAbsolutePath() + File.separator +*/
                        (dbName.toUpperCase().endsWith(".DB") ? dbName : dbName + ".db"), version);
            }
            openHelperMap.put(dbName, dbh5OpenHelper);
            encryptKeyMap.put(dbName, TextUtils.isEmpty(dbEncrypPwd) ? DEFAULT_DB_ENCRYP_PASD : dbEncrypPwd);
            return "true";
        } catch (Exception e) {
            return e.getLocalizedMessage();
        }
    }

    public SQLiteDatabase getWriteDatabase(String dbName) {
        DBH5OpenHelper dbh5OpenHelper = openHelperMap.get(dbName);
        if (dbh5OpenHelper != null) {
            return dbh5OpenHelper.getWritableDatabase(encryptKeyMap.get(dbName));
        } else {
            throw new RuntimeException("openHelperMap == null,请确认是否init" + dbName);
        }
    }

    /**
     * 关闭指定数据库
     *
     * @param dbName
     */
    public String closeSqliteHelper(String dbName) {
        if (openHelperMap != null) {
            DBH5OpenHelper dbh5OpenHelper = openHelperMap.get(dbName);
            if (dbh5OpenHelper != null) {
                dbh5OpenHelper.close();
                openHelperMap.remove(dbName);
                return "true";
            } else {
                Log.d(TAG, "closeSqliteHelper() returned: 找不到数据库dbName=" + dbName);
                return "找不到数据库dbName=" + dbName;
            }
        } else {
            Log.d(TAG, "closeSqliteHelper: dbh5OpenHelper == null,请确认是否init");
            return "closeSqliteHelper: dbh5OpenHelper == null,请确认是否init";
        }
    }

    /**
     * 关闭所有数据库
     */
    public String closeAllSqliteHelper() {
        String isAllClosed = "";
        if (openHelperMap != null) {
            for (Map.Entry<String, DBH5OpenHelper> entry : openHelperMap.entrySet()) {
                isAllClosed = closeSqliteHelper(entry.getKey());
                if (!isAllClosed.equals("true")) {
                    break;
                } else {
                    openHelperMap.remove(entry.getKey());
                }
            }
        } else {
            isAllClosed = "closeAllSqliteHelper:dbh5OpenHelper == null,请确认是否init";
            Log.e(TAG, "closeAllSqliteHelper:dbh5OpenHelper == null,请确认是否init ");
        }
        return isAllClosed;
    }
}
